package com.jc.service.jg;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jc.cds.model.CustomSupplierProduct;
import com.jc.common.util.Base64Util;
import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.ImageUtil;
import com.jc.common.util.UrlUtil;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.OrderProducts;
import com.jc.ds.model.SupplierGoods;
import com.jc.ds.model.SupplierGoodsPictureList;
import com.jc.ds.model.SupplierProduct;
import com.jc.ds.model.SupplierProductPrice;
import com.jc.ds.model.Xorder;
import com.jc.ds.model.XorderMarge;
import com.jc.framework.enums.Booleans;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.GoodNatureType;
import com.jc.framework.enums.GoodsDescType;
import com.jc.framework.enums.ImageType;
import com.jc.framework.enums.OrderStatus;
import com.jc.framework.enums.Push;
import com.jc.framework.enums.SystemUser;
import com.jc.framework.exception.ServiceException;
import com.jc.service.attribute.AttributeService;
import com.jc.service.h5.ShopService;
import com.jc.service.jg.mq.MqUtil;
import com.jc.service.model.jg.GoodsDetail;
import com.jc.service.model.jg.GoodsNavigate;
import com.jc.service.model.jg.GoodsSendVo;
import com.jc.service.model.jg.Inventory;
import com.jc.service.model.jg.ProductSendVo;
import com.jc.service.model.jg.RequestBaseModel;
import com.jc.service.model.yx.YanXuanResult;
import com.jc.service.order.XorderService;
import com.jc.service.orderproduct.OrderProductsService;
import com.jc.service.supplier.SupplierService;
import com.jc.service.suppliergoods.SupplierGoodsService;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListService;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListServiceImpl;
import com.jc.service.supplierproduct.SupplierProductService;
import com.jc.service.supplierproduct.SupplierProductServiceImpl;
import com.jc.service.supplierproductprice.SupplierProductPriceService;
import com.jc.service.xordermarge.XorderMargeService;
import com.jc.service.xorderprocess.XorderProcessService;
import com.jc.upload.aliyun.oos.AliyunOssUtil;

@SuppressWarnings("all")
@Service
public class JgServiceImpl implements JgService {

	Logger log = LoggerFactory.getLogger(JgServiceImpl.class);

	@Autowired
	SupplierGoodsService supplierGoodsService;
	@Autowired
	SupplierGoodsPictureListService supplierGoodsPictureListService;
	@Autowired
	SupplierProductService supplierProductService;
	@Autowired
	SupplierService supplierService;
	@Autowired
	AttributeService attributeService;
	@Autowired
	SupplierProductPriceService supplierProductPriceService;
	@Autowired
	ShopService shopService;
	@Autowired
	XorderService xorderService;
	@Autowired
	XorderMargeService xorderMargeService;
	@Autowired
	XorderProcessService xorderProcessService;
	
	@Autowired
	OrderProductsService orderProductsService;
	
	
	
	@Override
	public void receiveGoodsData(RequestBaseModel model) {
		try {
			List<GoodsSendVo> goodsSendVoList = JSON.parseObject(Base64Util.decode(model.getData()),
					new TypeReference<List<GoodsSendVo>>() {
					});
			for (GoodsSendVo goods : goodsSendVoList) {
				MqUtil.queue.put(goods);
			}
		} catch (Exception e) {
			throw new ServiceException(e);
		} 
	}

	public void saveGoodsPicture(GoodsSendVo goods) throws Exception {
//		String localPath = "/usr/local/jg/";
//		String datestr = DateTimeUtil.getDate(new Date(), "yyyyMMdd");
//
//		String goodsName = goods.getName();
//		if (StringUtils.isBlank(goodsName)) {
//			goodsName = "" + goods.getId();
//		}
//		String slocalPath = localPath + datestr + "/" + goodsName;
//		String sslocalPath = localPath + datestr + "/压缩后/" + goodsName;

//		String tit = "轮播图";
//		List<GoodsNavigate> goodsNavigateList = goods.getGoodsNavigateList();

//		for (GoodsNavigate na : goodsNavigateList) {
//			String url = na.getNavigateImage();
//			String fileName = UUID.randomUUID().toString().replaceAll("-", "");
//			if (!StringUtils.isBlank(url)) {
//				// 取扩展名
//				String extName = UrlUtil.getFileExtension(url);
//
//				String filePath = slocalPath + "/" + tit + "/" + fileName + "." + extName;
//				File f = new File(slocalPath + "/" + tit + "/");
//				if (!f.exists()) {
//					f.mkdirs();
//				}
//				String fileYaSuoPath = sslocalPath + "/" + tit + "/" + fileName + "." + extName;
//				File f2 = new File(sslocalPath + "/" + tit + "/");
//				if (!f2.exists()) {
//					f2.mkdirs();
//				}
//
//				ImageUtil.downloadPicture(url, filePath);
//				ImageUtil.outputQuality(filePath, 0.5, fileYaSuoPath, new BigDecimal("100"));
//			}
//		}

//		String tit2 = "详情图";
//		List<GoodsDetail> goodsDetailList = goods.getGoodsDetailList();
//
//		for (GoodsDetail gd : goodsDetailList) {
//			String url = gd.getImagePath();
//			String fileName = UUID.randomUUID().toString().replaceAll("-", "");
//			if (!StringUtils.isBlank(url)) {
//				String extName = UrlUtil.getFileExtension(url);
//
//				String filePath = slocalPath + "/" + tit2 + "/" + fileName + "." + extName;
//				File f = new File(slocalPath + "/" + tit2 + "/");
//				if (!f.exists()) {
//					f.mkdirs();
//				}
//				String fileYaSuoPath = sslocalPath + "/" + tit2 + "/" + fileName + "." + extName;
//				File f2 = new File(sslocalPath + "/" + tit2 + "/");
//				if (!f2.exists()) {
//					f2.mkdirs();
//				}
//				ImageUtil.downloadPicture(url, filePath);
//				ImageUtil.outputQuality(filePath, 0.5, fileYaSuoPath, new BigDecimal("100"));
//				log.error("  <<<<<<<<<<< 已经保存一张详情图...... :  " + goodsName);
//			}
//		}

		saveGoodsInfo(goods);
	}

	@Transactional
	public void saveGoodsInfo(GoodsSendVo goods) {
		String supplier_id = "45";
		// 保存货品信息
		SupplierGoods _supplier_goods = new SupplierGoods();
		_supplier_goods.setSupplierId(Integer.parseInt(supplier_id));
		_supplier_goods.setSupplierName("吉贡电商");
		if (goods != null && goods.getId() > 0) {
			_supplier_goods.setSupplierGoodsId(String.valueOf(goods.getId()));
		}

		// 防重复写入
		// existList
		List<SupplierGoods> existList = supplierGoodsService.queryAll(_supplier_goods);

		if (CollectionUtils.isNotEmpty(existList)) {
			_supplier_goods.setId(existList.get(0).getId());
			// 暂时返回后面要写更新产品逻辑
			// 与技术沟通后后，对于吉贡渠道商口，后面更新的话，需要更新三个字段，（产品名称，价格，规格）本次不做更新逻辑
		} else {
			if (goods != null && goods.getBrandId() > 0) {
				_supplier_goods.setBrandid(Long.valueOf(goods.getBrandId()));
			}
			if (goods != null && StringUtils.isNotBlank(goods.getName())) {
				_supplier_goods.setName(goods.getName());
			}
			if (goods != null && StringUtils.isNotBlank(goods.getBrandNameCn())) {
				_supplier_goods.setBrandnamecn(goods.getBrandNameCn());
			}
			if (goods != null && StringUtils.isNotBlank(goods.getBrandNameEn())) {
				_supplier_goods.setBrandnameen(goods.getBrandNameEn());
			}
			if (goods != null && goods.getCategoryId() > 0) {
				_supplier_goods.setCategoryId(goods.getCategoryId());
			}
			if (goods != null && StringUtils.isNotBlank(goods.getCategoryName())) {
				_supplier_goods.setCategoryName(goods.getCategoryName());
			}

			if (goods != null && goods.getCategoryParentId() > 0) {
				_supplier_goods.setCategoryParentId(goods.getCategoryParentId());
			}

			if (goods != null && StringUtils.isNotBlank(goods.getCategoryParentName())) {
				_supplier_goods.setCategoryParentName(goods.getCategoryParentName());
			}
			_supplier_goods.setGoodsDesc(GoodsDescType.PIC.toString());
			_supplier_goods.setGoodNatureType(GoodNatureType.MATERIAL.getName());
			_supplier_goods.setCreateTime(new Date());
			_supplier_goods.setLastUpdateTime(new Date());
			if (StringUtils.isNotBlank(goods.getSpecDesc())) {
				_supplier_goods.setSpecificationsString(goods.getSpecDesc());
				try {
					attributeService.initAttribute(goods.getSpecDesc());
				} catch (Exception e) {
				}
			}
			supplierGoodsService.add(_supplier_goods, false);

			// 保存货品轮播图信息
			List<GoodsNavigate> goodsNavigateList = goods.getGoodsNavigateList();
			for (GoodsNavigate nav : goodsNavigateList) {
				SupplierGoodsPictureList _nav = new SupplierGoodsPictureList();
				_nav.setGid(_supplier_goods.getId());
				if (StringUtils.isNotBlank(nav.getNavigateImage())) {
					_nav.setImagePath(nav.getNavigateImage());

					String selfImageUrl = imageZipUpload(nav.getNavigateImage());
					_nav.setSelfImagePath(selfImageUrl);

				}
				_nav.setImageType(ImageType.ROTATION.getName());
				if (goods != null && goods.getId() > 0) {
					_nav.setGoodsId("" + goods.getId());
				}
				supplierGoodsPictureListService.add(_nav, false);
			}
			// 保存货品详情图信息
			List<GoodsDetail> goodsDetailList = goods.getGoodsDetailList();
			for (GoodsDetail detailPic : goodsDetailList) {

				SupplierGoodsPictureList _nav = new SupplierGoodsPictureList();
				_nav.setGid(_supplier_goods.getId());
				if (StringUtils.isNotBlank(detailPic.getImagePath())) {
					_nav.setImagePath(detailPic.getImagePath());
					String selfImageUrl = imageZipUpload(detailPic.getImagePath());
					_nav.setSelfImagePath(selfImageUrl);
				}
				if (detailPic.getImageHeight() > 0) {
					_nav.setHeight(detailPic.getImageHeight());
				}
				if (detailPic.getImageWidth() > 0) {
					_nav.setWidth(detailPic.getImageWidth());
				}
				if (detailPic.getOrderNo() > -1) {
					_nav.setImageOrder(detailPic.getOrderNo());
				}
				_nav.setImageType(ImageType.DETAILS.getName());
				if (goods != null && goods.getId() > 0) {
					_nav.setGoodsId("" + goods.getId());
				}

				if (supplierGoodsPictureListService == null) {
					supplierGoodsPictureListService = new SupplierGoodsPictureListServiceImpl();
				}
				supplierGoodsPictureListService.add(_nav, false);
			}

		}

		// 保存SKU信息
		List<ProductSendVo> products = goods.getProducts();
		for (ProductSendVo vo : products) {
			SupplierProduct sp = new SupplierProduct();
			if (vo.getId() > 0) {
				sp.setProductId(String.valueOf(vo.getId()));
			}
			if (_supplier_goods.getId() > 0) {
				sp.setGid(_supplier_goods.getId());
			}
			Inventory inventory = vo.getInventory();
			List<SupplierProduct> queryAll = supplierProductService.queryAll(sp);
			if (CollectionUtils.isNotEmpty(queryAll)) {
				SupplierProduct to = queryAll.get(0);
				if (inventory != null) {
					to.setInventoryNum(inventory.getInventoryNum());
					to.setInventoryId("" + inventory.getId());
					to.setStoreId(""+inventory.getStoreId());
					to.setProductInventoryId(""+inventory.getId());
					supplierProductService.modify(to, false);
				}
				continue;
			}
			if (goods != null && StringUtils.isNotBlank(goods.getName())) {
				sp.setProductName(goods.getName());
			}
			
			if (inventory != null && inventory.getId() > 0) {
				
			}
			if (inventory != null) {
				sp.setInventoryNum(inventory.getInventoryNum());
				if(inventory.getId() > 0)sp.setInventoryId("" + inventory.getId());
				if(inventory.getStoreId() > 0)sp.setStoreId(""+inventory.getStoreId());
				if(inventory.getId() > 0)sp.setProductInventoryId(String.valueOf(inventory.getId()));
			}
			
			if (StringUtils.isNotBlank(vo.getImagePath())) {
				sp.setProductImagePath(vo.getImagePath());
				String selfImageUrl = imageZipUpload(vo.getImagePath());
				sp.setSelfProductImagePath(selfImageUrl);
			}
			if (StringUtils.isNotBlank(vo.getBarCode())) {
				sp.setBarCode(vo.getBarCode());
			}
			if (vo.getHasTax() >= 0) {
				sp.setHastax(vo.getHasTax());
			}

			if (goods != null && goods.getId() > 0) {
				sp.setGoodsId(String.valueOf(goods.getId()));
			}

			if (StringUtils.isNotBlank(vo.getSpecDesc())) {
				sp.setSpecificationsString(vo.getSpecDesc());
			}
			sp.setPushStatus(Push.WAIT_PUSH.getName());
			if (supplierProductService == null)
				supplierProductService = new SupplierProductServiceImpl();
			supplierProductService.add(sp, false);

			int freight = inventory.getDefaultFreight();
			// 保存SKU价格信息，涉及到有计算
			int private_cost_price = 0;//成本价,因为现在是全场包邮,所以这里要全部加上邮费
			int salePrice = 0; //市场价，因为现在是全场包邮,所以这里要全部加上邮费
			if (vo.getHasTax() == 0) {// 不含税
				private_cost_price = inventory.getCooperatePrice() + freight;
			} else {
				private_cost_price = inventory.getTaxCooperatePrice() + freight;
			}
			salePrice = inventory.getSalePrice() + freight;
			// 求差价
			int diffPrice = salePrice - private_cost_price;
			if (diffPrice < 0) {
				log.error("严重警告 ,出现负数................................... 产品SKU ID : " + vo.getId());
				continue;
			}
			int step = diffPrice / 4; // 四个等级，每级的差价
			SupplierProductPrice _supplierProductPrice = new SupplierProductPrice();
			_supplierProductPrice.setSupplierProductId(sp.getId());
			_supplierProductPrice.setDefaultFreight(freight);
			_supplierProductPrice.setCooperateprice(inventory.getCooperatePrice());
			_supplierProductPrice.setTaxcooperateprice(inventory.getTaxCooperatePrice());
			_supplierProductPrice.setSaleprice(salePrice);
			_supplierProductPrice.setMoneyPrice(salePrice);
			_supplierProductPrice.setLeve1Price(private_cost_price + step + step + step);
			_supplierProductPrice.setLeve2Price(private_cost_price + step + step);
			_supplierProductPrice.setLeve3Price(private_cost_price + step);
			_supplierProductPrice.setLeve4Price(private_cost_price);
			_supplierProductPrice.setCostPrice(private_cost_price);
			_supplierProductPrice.setUnionCostPrice(private_cost_price);
			supplierProductPriceService.add(_supplierProductPrice, false);
		}

	}

	@Transactional
	@Override
	public void updateProNum(Long productId) {
		//修改
		List<CustomSupplierProduct> customSupplierProducts = supplierProductService.selectProductByLimitOrSupplierName(new HashMap<String, Object>() {{
			put("start", 0);
			put("limit", 1);
			put("supplierName", "吉贡云");
			put("productId", productId);
		}});
		if (CollectionUtils.isEmpty(customSupplierProducts)){
			throw new BaseServiceException("产品SKU不存在 id "+ productId);
		}
		supplierProductService.modify(new SupplierProduct(){{
			setId(customSupplierProducts.get(0).getId());
			setInventoryNum(0);
		}},false);
		shopService.pushInventory(customSupplierProducts.get(0).getId(),"0");
	}

	/***
	 * 下载远程图片,存本地，并进行压缩，最后上传阿里云获取外网访问地址 @Title: imageZipUpload @Description:
	 * TODO @param @param remoteUrl @return void @throws
	 */
	public String imageZipUpload(String remoteUrl) {
		String localPath = "/usr/local/jg/";
		String datestr = DateTimeUtil.getDate(new Date(), "yyyyMMdd");
		try {
			String path = localPath + datestr;
			File dir = new File(path);

			if (!dir.exists()) {
				dir.mkdirs();
			}
			String name = UUID.randomUUID().toString().replaceAll("-", "");
			String extName = UrlUtil.getFileExtension(remoteUrl);
			String notZipFilePath = path + "/" + name + "." + extName;
			String zipFilePath = path + "/" + "zip" + name + "." + extName;
			ImageUtil.downloadPicture(remoteUrl, notZipFilePath);
			String localhostPath = ImageUtil.outputQuality(notZipFilePath, 0.5, zipFilePath, new BigDecimal("100"));
			// 上传
			AliyunOssUtil util = new AliyunOssUtil();
			String imageURL = util.uploadImg2Oss(new File(localhostPath));
			return imageURL;
		} catch (Exception e) {
			log.error("压缩上传图片出现错误, 图片源地址: {} , 错误原因: {},{}", remoteUrl, e.getMessage(), e);
		}

		return null;
	}

	@Transactional
	public Map<String,Object> addJgOrderExpress(String supplier_child_order_id, String expressName,String expressNo) {
		Map<String,Object> ret = new HashMap<String, Object>();
		if(StringUtils.isBlank(supplier_child_order_id)) {
			ret.put("code", 9999);
			ret.put("message", "orderSn 参数不参为空 !");
			return ret;
		}
		
		OrderProducts _query = new OrderProducts();
		_query.setSupplierChildOrderId(supplier_child_order_id);
		List<OrderProducts> _list = orderProductsService.queryAll(_query);
		if(CollectionUtils.isEmpty(_list)) {
			ret.put("code", 9999);
			ret.put("message",supplier_child_order_id + " 这个子订单号在集呈系统中不存在 !");
			return ret;
		}
		
		
		for(OrderProducts p : _list) {
			p.setExpressCompany(expressName);
			p.setExpressNo(expressNo);
			orderProductsService.modify(p, false);
			
			//找到父订单修改父订单状态,并推送商城
			Long orderid = p.getOrderId();
			if(orderid != null) {
				Xorder updateOrder = xorderService.queryById(orderid);
				updateOrder.setOrderStatus(OrderStatus.outstorage.getName());
				updateOrder.setExpressName(expressName);
				updateOrder.setExpressNo(expressNo);
				updateOrder.setUpdateTime(new Date());
				xorderService.modify(updateOrder, false);
				//记录订单日志
				xorderProcessService.addXorderProcess(updateOrder.getChannelOrderId(), "订单已经由吉贡发货", SystemUser.ADMIN.getName(), updateOrder.getId());
				//推送商城
				shopService.pushOrder(updateOrder.getChannelOrderId());
			}
		}
		
		ret.put("code", 10000);
		ret.put("message","ok");
		
		return ret;
	}
	
	
	
	/**
	 * 暂时有些问题，先不实现,因为OMS合并多个STORE_ID的订单推送到吉贡平台，
	 * 如果多个STORE各自发货后，针对该笔合并订单会产生多个物流单号,但是目前该渠道回调整API只返回一条物流信息，
	 * 需要和平台技术联系确认，这种情况的处理方式，后再进行实现。
	 * 吉贡渠道：请务必按STORE_ID进行合并订单,或者每个产品一个订单，除了这两种情况外，其它订单执行下面方法会出现错误
	 * 
	 * **/
	public YanXuanResult addOrderExpress(String channelOrderId, String expressName,String expressNo) {
		
		
		
		YanXuanResult ret = new YanXuanResult();
		ret.setMessage(Conclusion.OK.getDesc());
		
		//先查询有没有多次推送的临时订单号记录
		//查看有没有多次推送的记录，找到最后一次推送记录,关联到原订单号
		XorderMarge xorderMargeByChannelOrder = xorderMargeService.getXorderMargeByChannelOrderId(channelOrderId);
		String effectiveChannelOrderId = "";
		if(xorderMargeByChannelOrder == null) { //无重复推送记录
			effectiveChannelOrderId = channelOrderId;
		}else { //有记录
			effectiveChannelOrderId = xorderMargeByChannelOrder.getChannelOrderId();
		}
		//查询有没有合并订单的记录
		List<XorderMarge> childOrderList = xorderMargeService.getChildOrderList(effectiveChannelOrderId);
		String parentOrderId = null;
		List<Xorder> orderList = new ArrayList<Xorder>();
		
		if(CollectionUtils.isEmpty(childOrderList)) {//无合单记录
			Xorder queryOrder = new Xorder();
			queryOrder.setChannelOrderId(channelOrderId);
			queryOrder.setIsDelete(Booleans.FALSE.getName());
			List<Xorder> olist = xorderService.queryAll(queryOrder);
			if(CollectionUtils.isEmpty(olist)) {
				ret.setCode(99999);
				ret.setMessage( channelOrderId +  " 订单不存在,无法出库");
				return ret;
			}
			if(olist.size() > 1) {
				ret.setCode(99999);
				ret.setMessage( channelOrderId +  " 订单在订单表存在两条以上记录,无法出库");
				return ret;
			}
			orderList = olist;
		}else {//有合单记录
			parentOrderId = channelOrderId;
			for(XorderMarge mg : childOrderList) {
				Long childOrderId = mg.getOrderId();
				orderList.add(xorderService.queryById(childOrderId));
			}
		}
		
		
		
		for(Xorder o : orderList) {
			if(StringUtils.equals(o.getOrderStatus(), OrderStatus.outstorage.getName())) continue;
			o.setExpressNo(expressNo);
			o.setExpressName(expressName);
			o.setOrderStatus(OrderStatus.outstorage.getName());
			o.setUpdateTime(new Date());
			xorderService.modify(o, false);
			//推送商城
			String code = shopService.pushOrder(o.getChannelOrderId());
			if(code != null && StringUtils.equals("0", code)) {
				xorderProcessService.addXorderProcess(o.getChannelOrderId(), "订单推送商城成功", SystemUser.ADMIN.getName(), o.getId());
			}else {
				xorderProcessService.addXorderProcess(o.getChannelOrderId(), "订单推送商城过程中发生错误,处理失败", SystemUser.ADMIN.getName(), o.getId());
			}
		}
		
		
		if(StringUtils.isNotBlank(parentOrderId)) { //更新父订单的状态和运单号
			Xorder queryOrder = new Xorder();
			queryOrder.setChannelOrderId(parentOrderId);
			queryOrder.setIsDelete(Booleans.FALSE.getName());
			List<Xorder> olist = xorderService.queryAll(queryOrder);
			if(CollectionUtils.isEmpty(olist)) {
				ret.setCode(99999);
				ret.setMessage( parentOrderId +  " 父订单不存在,无法出库");
				return ret;
			}
			if(olist.size() > 1) {
				ret.setCode(99999);
				ret.setMessage( parentOrderId +  " 父订单在订单表存在两条以上记录,无法出库");
				return ret;
			}
			Xorder updateOrder = olist.get(0);
			updateOrder.setOrderStatus(OrderStatus.outstorage.getName());
			updateOrder.setExpressNo(expressNo);
			updateOrder.setUpdateTime(new Date());
			xorderService.modify(updateOrder, false);
		}
		return ret;
	}
	
	
	


}
